#include "Buffer.h"

#ifndef ZERO 
	#define ZERO 0
#endif


Buffer* Buffer::GetInstance()
{
	static Buffer instance;
	
	return &instance;
}

Buffer::Buffer()
	:size(ZERO)
{
	for(unsigned int i = ZERO; i < LINKED_MAX; i++)
		vList[i] = new List();
}

Buffer::~Buffer()
{
	size = ZERO;
	for(unsigned int i = ZERO; i < LINKED_MAX; i++)
		delete vList[i];
}

int Buffer::hashFunction(int handler, int offset)
{
	return ((handler * offset) % LINKED_MAX);
}

int Buffer::get(int handler, int offset, void* ptr, unsigned int &sizePtr)
{	
	RecordBuffer element;
	int pos = this->hashFunction(handler, offset);
	List* lista = vList[pos];

	element.setKey(handler, offset);
	
	if(lista->get(&element))
	{
		element.get(handler, offset, (char*)ptr, sizePtr);
		return RES_OK;
	}
	else
		return RES_ERROR;
}

void Buffer::add(int handler, int offset, void* ptr, unsigned int sizePtr)
{
	RecordBuffer element;
	int pos = this->hashFunction(handler, offset);
	List* lista = vList[pos];

	element.set(handler, offset, (char*)ptr, sizePtr);
	
	if(lista->get(&element))
	{
		lista->remove(&element);
		size -= element.getSize();
	}

	if(size + sizePtr > BUFFER_MAX_SIZE)
	{
		delete lista;
		lista = vList[pos] = new List();
	}
	lista->add(&element);
}


